package com.example.lib_base


import android.app.VoiceInteractor
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File

object DownloadUtil {
    fun download(url: String, file: File): Flow<UIState> {
        return flow {
            //发起请求
            val request = Request.Builder().url(url).get().build()
            //请求的返回
            val response = OkHttpClient.Builder().build().newCall(request).execute()
            //判断请求是否成功
            if (response.isSuccessful) {
                //请求成功
                response.body.let { body ->
                    file.outputStream().let { os ->
                        //从body中获取的字节流,下载的内容
                        val bs = body?.byteStream()
                        //默认的文件或者字节长度
                        var len = 0
                        //声明的字节数组,默认DEFAULT_BUFFER_SIZE缓冲去的大小
                        val byteArray = ByteArray(DEFAULT_BUFFER_SIZE)
                        //.also { len = it!! } 将读取到的字节数赋值给len
                        //while 的条件是字节数不为-1
                        while (bs?.read(byteArray).also { len = it!! } != -1) {
                            //把下载到的字节数组,写入到文件中(通过outputStream来写入)
                            os.write(byteArray, 0, len)
                        }
                        //刷新输出流,确保所有缓冲的数据都被写入目标
                        os.flush()
                        //关闭
                        os.close()
                        //发送成功的状态
                        emit(UIState.OnSuccess("下载完成", HttpType.DOWNLOAD))
                    }
                }
            } else {
                //通过flow发送数据
                emit(UIState.OnError("下载失败"))
            }
        }
    }
}